<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" size="small">
    <el-form-item label="商品名称" prop="goodsName">
      <el-input v-model.trim="ruleForm.goodsName" placeholder="请输入商品名称"></el-input>
    </el-form-item>

    <el-form-item label="商品简介" prop="goodsSummary">
      <el-input
        v-model.trim="ruleForm.goodsSummary"
        placeholder="请输入商品简介"
        type="textarea"
        :rows="4"
      ></el-input>
    </el-form-item>

    <el-form-item label="商品图" prop="goodsPictureMain">
      <el-input v-model="ruleForm.goodsPictureMain" class="hide" />
      <el-upload
        :action="$V.uploadURL"
        :headers="{token: $getToken()}"
        :on-success="(...args) => handleUploadSuccess('goodsPictureMain', ...args)"
        :on-remove="(...args) => handleUploadRemove('goodsPictureMain', ...args)"
        :on-error="handleUploadError"
        :file-list="mainFileList"
        :multiple="false"
        :limit="1"
        :class="single ? 'single' : ''"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>

    <el-form-item label="封面图" prop="goodsPicture">
      <el-input v-model="ruleForm.goodsPicture" class="hide" />
      <el-upload
        :action="$V.uploadURL"
        :headers="{token: $getToken()}"
        :on-success="(...args) => handleUploadSuccess('goodsPicture', ...args)"
        :on-remove="(...args) => handleUploadRemove('goodsPicture', ...args)"
        :on-error="handleUploadError"
        :file-list="coverFileList"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="商品原价" prop="goodsPriceOriginal">
      <el-input v-model.trim="ruleForm.goodsPriceOriginal" placeholder="请输入商品原价"></el-input>
    </el-form-item>

    <el-form-item label="商品现价" prop="goodsPriceDiscount">
      <el-input v-model.trim="ruleForm.goodsPriceDiscount" placeholder="请输入商品现价"></el-input>
    </el-form-item>

    <el-form-item label="所属供应商" prop="goodsSupplier">
      <el-select v-model="ruleForm.goodsSupplier" placeholder="请选择所属供应商" class="block">
        <el-option
          v-for="(it,key) in $attrs.supplySelects"
          :label="it.label"
          :value="it.value"
          :key="key"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="商品分类" prop="classifyIdList">
      <el-select v-model="ruleForm.classifyIdList" placeholder="请选择商品分类" multiple class="block">
        <el-option
          v-for="(it,key) in $attrs.categorySelects"
          :label="it.label"
          :value="it.value"
          :key="key"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="商品详情" prop="goodsDetailed">
      <t-editor v-model.trim="ruleForm.goodsDetailed"></t-editor>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSubmit">{{actionText}}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
/* Mixins
------------------------------- */
import { Form } from '@/mixins'

/* Components
------------------------------- */
import TEditor from '@/components/editor/Editor'

/* Api
------------------------------- */
import { checkFreshFoodsName } from '@/api'

/* Model
------------------------------- */
import { maintenanceGoodsModel, primaryKey } from '../model'

export default {
  mixins: [Form('ruleForm', maintenanceGoodsModel)],
  components: {
    TEditor
  },
  data () {
    const asyncCheckFreshGoodsName = (rule, value, callback) => {
      return this.checkFreshFoodsName(
        {
          name: value,
          id: this.ruleForm[primaryKey]
        },
        {
          onOk ({ data }) {
            !data ? callback(new Error('当前商品名称已存在')) : callback()
          },
          onError ({ message }) {
            callback(new Error(message))
          }
        }
      )
    }

    return {
      ruleForm: Object.assign({}, maintenanceGoodsModel),
      rules: {
        goodsName: [
          {
            required: true,
            message: this.$t('required', { field: '商品名称' })
          },
          { validator: asyncCheckFreshGoodsName, trigger: 'blur' }
        ],
        goodsSummary: [
          {
            required: true,
            message: this.$t('required', { field: '商品简介' })
          }
        ],
        classifySort: [
          {
            required: true,
            message: this.$t('required', { field: '分类排序' })
          }
        ],
        goodsPicture: [
          {
            required: true,
            message: this.$t('required', { field: '封面图' })
          }
        ],
        goodsPictureMain: [
          {
            required: true,
            message: this.$t('required', { field: '商品图' })
          }
        ]
      },
      single: false,
      mainFileList: [],
      coverFileList: []
    }
  },
  methods: {
    // --------------------------------------  request --------------------------------------
    checkFreshFoodsName ({ name, id }, { onOk, onError }) {
      return this.Catch(checkFreshFoodsName, {
        onOk,
        onError
      })(null, name, id)
    },

    handleUploadSuccess (field, res, file, fileList) {
      if (res.result !== httpStatus.OK) {
        this.$message.error(res.message)
        return
      }

      if (field === 'goodsPictureMain') {
        this.ruleForm[field] = res.data
        this.single = fileList.length === 1
      }

      if (field === 'goodsPicture') {
        this.ruleForm[field] = fileList
          .map((it) => (it.response && it.response.data) || it.name)
          .join(',')
      }
    },
    handleUploadError (_, file, fileList) {
      this.$message.error(this.$t('fileUploadError'))
    },
    handleUploadRemove (field, file, fileList) {
      if (field === 'goodsPictureMain') {
        this.ruleForm['goodsPictureMain'] = ''
        this.single = false
      } else {
        this.ruleForm[field] = fileList
          .map((it) => (it.response && it.response.data) || it.name)
          .join(',')
      }
    },

    // -------------------------------------- !request --------------------------------------

    handleSubmit () {
      try {
        this.submit((valid, values) => {
          if (valid) {
            this.$emit('submit', values)
          }
        })
      } catch (err) {
        this.$message.error(err.message)
      }
    },

    updateMainFileList () {
      this.mainFileList = this.ruleForm.goodsPictureMain
        .split(',')
        .filter(Boolean)
        .map((it) => {
          return {
            name: it,
            url: this.$V.staticBaseURL + it
          }
        })
      this.single = this.mainFileList.length > 0
    },
    updateCoverFileList () {
      this.coverFileList = this.ruleForm.goodsPicture
        .split(',')
        .filter(Boolean)
        .map((it) => {
          return {
            name: it,
            url: this.$V.staticBaseURL + it
          }
        })
    }
  },
  computed: {
    actionType () {
      return this.ruleForm[primaryKey] ? 'update' : 'create'
    },
    actionText () {
      return this.actionType === 'create'
        ? this.$t('createText')
        : this.$t('updateText')
    }
  },

  mounted () {
    this.updateMainFileList()
    this.updateCoverFileList()
    this.watchSelect(
      'goodsSupplier',
      'goodsSupplierName',
      this.$attrs.supplySelects
    )
  }
}
</script>

<style scoped lang="scss">
.spec-form {
  .creation {
    margin-top: -1px;
  }
  >>> &.el-form {
    .el-form-item {
      margin-bottom: 0;
    }
    .el-input__inner {
      border: none;
    }
  }
}

.table {
  width: 100%;
  font-size: 12px;
  tr {
    border-bottom: 1px solid #dedede;
    border-left: 1px solid #dedede;
    border-right: 1px solid #dedede;
  }
  th {
    border-top: 1px solid #dedede;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    border-bottom: 1px solid #dedede;
    transition: background 0.3s ease;
  }
  td {
    text-align: center;
    //  border-right: 1px solid #dedede;
  }
}
</style>
